require(xtable)
require(data.table)
## total number of pages
.ntabs <- 15

## see ?mtcars for details

#.x <- 'mpg'
.y <- c('disp', 'hp', 'wt')


## for each table, make the draws and record everything 
## pages 1-N

.nrow <- nrow(mtcars)
tablist <- llply(1:.ntabs, function(.n) {
        ## just get 10 samples per
        .sample <- sample(1:.nrow, 10, replace=F)
        .dat <- mtcars[.sample,]
        .dat <- .dat[order(.dat$mpg),]
        ## different responses for different folks
        .response.name <- .y[(.n%%3)+1] 
        ret <- data.frame(MPG = .dat$mpg)
        ret[["X Rank"]] <- 10:1
        ret[[ .response.name ]] <- .dat[[.response.name]]
        ret[["Y Rank"]] <- ""
        ret[["Rank difference"]] <- ""
        ret[["Squared difference"]] <- ""
        ret
})

## print all the tables here
.filename <- 'wk10-xtabs.tex'

## convenience function,
## takes the list and prints data as table, along w/id
my.print.xtab <- function(x, n) {
    .heading = sprintf('\n\\\\centering\nTable %d\n\n', n)
    system(sprintf(" echo '%s' >> %s", .heading, .filename))
    print(
        xtable(x, digits=2), 
        file=.filename,
        append=T,
        include.rownames=F,
        include.colnames=T
    )
}

## clear out the .tex file to start
system(sprintf('echo " " > %s', .filename))
## for each page, print small and large tables
l_ply(1:.ntabs, function(n){
    .dat <- tablist[[n]]
    my.print.xtab(.dat, n)
    system(sprintf(" echo '\\\\clearpage\n' >> %s", .filename))
})



if(F){
## print thrice
for(ii in 1:3) {
    print(xtable(tab.ids, digits=0), include.rownames=F, include.colnames=T, file=.filename, append=T)
    system(sprintf(" echo '\\\\clearpage\n' >> %s", .filename))
}
}
